<template>
  <div class="upload">
    <a-upload :beforeUpload="beforeUpload"
              :headers="{'X-Requested-With': null}"
              @change="handleChange"
              :action="uploadUrl"
              :fileList="fileList"
              accept=".doc,.docx,.xlsx,.xls,.pdf,.jpg,.png">
      <p class="text-tip-x">
        <!-- 支持格式.doc .docx .pdf .xls .jpg .png, -->
        <span>单个文件最大10MB,最多可上传10个</span>
      </p>
      <a-button v-if="fileList.length<10">
        <a-icon type="upload" /> 上传附件 </a-button>
    </a-upload>

  </div>
</template>
<script>
import GlobalMixin from '@/mixins/global'
export default {
  name: 'uploadFiles',
  mixins: [GlobalMixin],
  data () {
    return {
      uploadUrl: process.env.VUE_APP_API + '/attach/upload?token=TGT-3836-1de90VaLW3ROf7lMd9l59TOaNo0S5mTHtyycJmeOoDt9IevDb6-cas',
      fileList: []
    }
  },
  props: {
    fileTypeStr: {
      type: Array,
      default: () => [
        'doc',
        'docx',
        'xlsx',
        'xls',
        'pdf',
        'jpg',
        'png']
    }
  },
  methods: {
    beforeUpload (e) {
      // eslint-disable-next-line promise/param-names
      return new Promise((reslove, reject) => {
        const fileTypeStr = this.fileTypeStr
        const isLt10M = e.size / 1024 / 1024 < 10
        if (!isLt10M) {
          this.$message.error('附件大于10MB，无法上传!')
          reject(new Error())
          return
        }
        let filename = e.name
        const index = filename.lastIndexOf('.')
        filename = filename.substr(index + 1)
        if (fileTypeStr.includes(filename.toLocaleLowerCase())) {
          reslove(true)
        } else {
          this.$message.error('文件格式不正确!')
          reject(new Error())
        }
      })
    },
    // 上传附件
    handleChange (info) {
      this.confirmLoading = true
      let fileList = [...info.fileList]
      this.fileList = fileList
      fileList = fileList.map(file => {
        if (file.response) {
          if (!file.response.flag) {
            file.status = 'error'
            this.$message.error(file.response.errMsg || '服务端发生错误')
            return
          }
        }
        return file
      })
    },
    changeState (e) {
      this.visible = e
    }
  }
}
</script>
